#include "head.h"
/* Usage: */

int pipe_fd[2];

void func(int num){
    write(pipe_fd[1], "1", 1);
}

int main(int argc, char *argv[])
{
    pipe(pipe_fd);
    if(fork()!=0){
        signal(2, func);
        wait(0);
        exit(0);
    }

    setpgid(0, 0);
    
    status_t status;
    initStatus(&status);

    

    int skt_fd;
    char ip[100];
    char port[100];
    char rootpath[100];
    getparameter("ip", ip);
    getparameter("port", port);
    getparameter("rootpath", rootpath);
    rootpath[strlen(rootpath)-1] = 0;
    //printf("%s %s\n", ip, port);
    initSocket(&skt_fd, ip, port);

    int epl_fd = epoll_create(1);
    addEpoll(epl_fd, skt_fd);
    addEpoll(epl_fd, pipe_fd[0]);

    mkdir("./userDir", 0777);
    chdir("./userDir");
    while(1){
        struct epoll_event eves[THNUM+2];
        int evenum = epoll_wait(epl_fd, eves, THNUM+2, -1);

        for(int i=0; i<evenum; i++){
            if(eves[i].data.fd==pipe_fd[0]){
                char buf[60] = {0};
                read(pipe_fd[0], buf, sizeof(buf));
                pthread_mutex_lock(&status.lock);
                status.exit_flag = true;
                pthread_cond_broadcast(&status.cond);
                pthread_mutex_unlock(&status.lock);
                for(int i=0; i<THNUM; i++){
                    pthread_join(status.thds[i], NULL);
                }
                exit(0);
            }
            if(eves[i].data.fd==skt_fd){
                int net_fd = accept(skt_fd, NULL, NULL);
                
                client_status *user = login(net_fd);
                user->net_fd = net_fd;
                strcpy(user->root_path, rootpath);
                printf("rootpath = %s\n", rootpath);
                printf("user->root_path = %s\n", user->root_path);
                strcat(user->root_path, user->user_name);
                strcat(user->root_path, "/");
                printf("已于用户 %s 建立连接：\n用户目录位于 %s\n", user->user_name, user->root_path);
                pthread_mutex_lock(&status.lock);
                push(status.net_q, user);
                pthread_cond_signal(&status.cond);
                pthread_mutex_unlock(&status.lock);
            }
        }
    }
    return 0;
}

